package com.yjd.msg.comm.aspect;

import com.alibaba.fastjson.JSON;
import com.yjd.msg.comm.annotation.MnsMsg;
import com.yjd.msg.comm.core.model.MnsMessage;
import com.yjd.msg.comm.util.MnsUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yjd-wap on 2018/1/19.
 */
@Aspect
@Order(value = 100001)
public class MnsAspect {

    private static Logger logger = Logger.getLogger(MnsAspect.class);

    @Around(value = "execution(* com.yjd..*ServiceImpl.*(..))")
    public Object invoke(ProceedingJoinPoint invocation) throws Throwable {
        boolean firstIn = false;
        boolean isOk = true;
        List<MnsMessage> list = MnsUtils.getMnsMessage();
        if (list == null) {
            firstIn = true;
            MnsUtils.setMnsMessage(new ArrayList<MnsMessage>());
        }
        try {
            Object result = invocation.proceed();
            return result;
        } catch (Exception e) {
            logger.info("####发消息的业务执行失败，异常信息:" + e);
            isOk = false;
            throw e;
        } finally {
            if (firstIn) {
                if (isOk) {
                    try {
                        MnsUtils.sendMessage();
                    } catch (Exception e) {
                        logger.info("####业务执行完成，第一次发送消息失败异常数据:"
                                + JSON.toJSONString(MnsUtils.getMnsMessage())
                                + " 异常信息:" + e);
                    }
                }
                MnsUtils.getThreadLocalList().remove();
            }
        }
    }
}